﻿Imports PdfSharp
Imports PdfSharp.Pdf
Imports PdfSharp.Drawing
Imports PdfSharp.Pdf.IO
Imports System.IO
Imports System

Module modulepdf
    Public cliente As String
    Public colore As String
    Public htesto As String
    Public odp As String
    Public posx As String
    Public posy As String
    Public quantita As String
    Public urgente As Boolean
    Public abilitawatermark As Boolean
    Public PARTENZA_TESTO_X As Double
    Public PARTENZA_TEST_Y As Double
    Public note As String
    Public destinazione As String
    Dim PUNTOSOPRA As Double
    Dim PUNTOSOTTO As Double
    Dim SCALARIDIMY As Double = 0.91


    Public Function crea_pdf(ByVal fileorigine As String, ByVal drawstate As String, Optional ByVal quantita_a_mag As String = "", Optional ByVal Destinazione As String = "")
        Dim file_modificato As String
        Dim document As PdfDocument
        'copio il file originale 
        Dim tempfile = Application.StartupPath & "\" & dati_stampa.Tempfile & ".pdf"
        Try
            File.Copy(fileorigine, tempfile, True)

            Dim emSize As Integer = 100
            'scelgo il font
            Dim font As New XFont("Arial Black", emSize, XFontStyle.BoldItalic)

            Dim gfx As XGraphics
            Dim i As Integer
            Dim page As PdfPage
            Dim size As XSize
            Dim SIZETOT As New XSize
            Dim format As XStringFormat
            Dim brush As XBrush

            If quantita_a_mag = "" Then
                quantita_a_mag = "0"
            End If


            'seleziono il file da aprire
            'document = PdfReader.Open(tempfile)
            If cliente = "" And Destinazione = "" And odp = "" And quantita = "" And colore = "" And note = "" And quantita_a_mag = "0" Then
            Else
                tempfile = RIDIMENSIONA_PDF(fileorigine)
            End If
            document = PdfReader.Open(tempfile)
ITEXTSTART:

            If abilitawatermark = True Then

                Dim watermark As String = ""

                If drawstate = "modifica" Then
                    watermark = "Da modificare"
                ElseIf drawstate = "provvisori" Then
                    watermark = "Modificati"
                ElseIf drawstate = "definitivi" Then
                    watermark = ""
                End If

                If (document.Version < 14) Then
                    document.Version = 14
                End If

                For i = 0 To document.Pages.Count - 1
                    page = document.Pages(i)

                    gfx = XGraphics.FromPdfPage(document.Pages(i))

                    'Prendo la grandezza (in point) del testo
                    size = gfx.MeasureString(watermark, font)

                    ' Spostiamo al centro , trasformiamo e ruotiamo
                    gfx.TranslateTransform(page.Width.Point / 2, page.Height.Point / 2)
                    gfx.RotateTransform(-Math.Atan(page.Height.Point / page.Width.Point) * 180 / Math.PI)
                    gfx.TranslateTransform(-page.Width.Point / 2 + 50, -page.Height.Point / 2 + 100)

                    'Creiamo  la string format
                    format = New XStringFormat()
                    format.Alignment = XStringAlignment.Near
                    format.LineAlignment = XLineAlignment.Near

                    ' Creiamo un colore rosso 
                    brush = New XSolidBrush(XColor.FromArgb(70, 255, 0, 0))

                    ' Scriviamo il testo
                    gfx.DrawString(watermark, font, brush, New XPoint((page.Width.Point - size.Width) / 2, (page.Height.Point - size.Height) / 2))

                Next
                ' Salvo
                document.Save(tempfile)
            End If

            document = PdfReader.Open(tempfile)
            emSize = htesto
            'scelgo il font
            ' font = New XFont("Arial Black", emSize, XFontStyle.Regular)
            font = New XFont("Arial Black", 15, XFontStyle.Regular)

            If (document.Version < 14) Then
                document.Version = 14
            End If

            For i = 0 To document.Pages.Count - 1
                page = document.Pages(i)

                gfx = XGraphics.FromPdfPage(document.Pages(i))


                If i = 0 Then
                    ' Spostiamo al centro , trasformiamo e ruotiamo
                    'gfx.TranslateTransform(page.Width.Point / 2, page.Height.Point / 2)

                    'Creiamo  la string format
                    format = New XStringFormat()
                    format.Alignment = XStringAlignment.Near
                    format.LineAlignment = XLineAlignment.Near

                    ' Creiamo un colore rosso 
                    brush = New XSolidBrush(XColor.FromArgb(150, 255, 0, 0))

                    SIZETOT.Width = 0
                    SIZETOT.Width += 10
                    If Destinazione <> Nothing Then
                        size = gfx.MeasureString("Reparto destinazione:" & Destinazione, font)
                        'gfx.DrawString(cliente, font, brush, New XPoint(page.Width.Millimeter - (page.Width.Millimeter - posx), page.Height.Millimeter - (page.Height.Millimeter - posy)))
                        gfx.DrawString("Reparto destinazione:" & Destinazione, font, brush, New XPoint(25, PUNTOSOPRA - size.Height / 2))

                    End If

                    If cliente <> Nothing Then
                        size = gfx.MeasureString(cliente & "  |  ", font)
                        'gfx.DrawString(cliente, font, brush, New XPoint(page.Width.Millimeter - (page.Width.Millimeter - posx), page.Height.Millimeter - (page.Height.Millimeter - posy)))
                        gfx.DrawString(cliente & "  |  ", font, brush, New XPoint(SIZETOT.Width, PUNTOSOTTO + size.Height / 2))
                        SIZETOT.Width += size.Width

                    End If
                    If odp <> Nothing Then
                        size = gfx.MeasureString("N. ORV: " & odp & "  |  ", font)
                        gfx.DrawString("N. ORV: " & odp & "  |  ", font, brush, New XPoint(SIZETOT.Width + 15, PUNTOSOTTO + size.Height / 2))
                        SIZETOT.Width += size.Width + 15

                    End If
                    If quantita <> Nothing Then
                        size = gfx.MeasureString("Q.tà: " & quantita & "  |  ", font)
                        gfx.DrawString("Q.tà: " & quantita & "  |  ", font, brush, New XPoint(SIZETOT.Width + 15, PUNTOSOTTO + size.Height / 2))
                        SIZETOT.Width += size.Width + 15

                    End If
                    If colore <> Nothing Then
                        size = gfx.MeasureString("RAL: " & colore & "  |  ", font)
                        gfx.DrawString("RAL: " & colore, font, brush, New XPoint(SIZETOT.Width + 15, PUNTOSOTTO + size.Height / 2))

                    End If

                    If note <> Nothing Then
                        size = gfx.MeasureString("*** " & note & " ***", font)
                        gfx.DrawString("*** " & note & " ***", font, brush, New XPoint((page.Width.Value / 2) - (size.Width / 2), PUNTOSOTTO + (size.Height * 1.2)))

                    End If

                    If quantita_a_mag = "" Or quantita_a_mag = "0" Then
                    Else
                        brush = New XSolidBrush(XColor.FromArgb(128, 0, 0, 255))
                        font = New XFont("Arial Black", 23, XFontStyle.Regular)
                        gfx.DrawString(quantita_a_mag & " A MAG.", font, brush, New XPoint(page.Width.Millimeter - (-242), 30))
                    End If

                    If urgente = True Then
                        brush = New XSolidBrush(XColor.FromArgb(128, 255, 0, 180))
                        font = New XFont("Arial Black", 23, XFontStyle.Regular)
                        gfx.DrawString("URGENTE", font, brush, New XPoint(page.Width.Millimeter - (-42), 30))
                    End If
                End If

            Next
            ' Salvo

            document.Save(tempfile)
            file_modificato = tempfile
            document.Close()

        Catch ex As PdfSharpException
            ' tempfile = tempfile

            Dim newName As MemoryStream = ReturnCompatiblePdf(tempfile)
            Dim reader As New PdfDocument
            reader = PdfReader.Open(newName, PdfDocumentOpenMode.Modify)
            document = reader
            document.Save(Application.StartupPath & "\" & dati_stampa.Tempfile & "STREAM.pdf")
            document.Close()
            reader = PdfReader.Open(RIDIMENSIONA_PDF(Application.StartupPath & "\" & dati_stampa.Tempfile & "STREAM.pdf"), PdfDocumentOpenMode.Modify)
            document = reader
            GoTo ITEXTSTART
        Catch ex1 As FileNotFoundException
            MsgBox(ex1.ToString)
        End Try
        Return file_modificato

    End Function


    'Public Module CompatiblePdfReader

    '        ''' <summary>
    '        ''' uses itextsharp 4.1.6 to convert any pdf to 1.4 compatible pdf, called instead of PdfReader.open
    '        ''' </summary>
    '        ''' <param name="sFilename"></param>
    '        ''' <returns></returns>
    '        Public Function Open(ByVal sFilename As String) As PdfDocument

    '            Dim reader As New PdfDocument()

    '            Try
    '                reader = PdfReader.Open(sFilename, PdfDocumentOpenMode.Import)
    '            Catch generatedExceptionName As PdfSharp.Pdf.IO.PdfReaderException
    '                'workaround if pdfsharp doesnt dupport this pdf
    '                Dim newName As MemoryStream = ReturnCompatiblePdf(sFilename)
    '                reader = PdfReader.Open(newName, PdfDocumentOpenMode.Import)
    '            End Try

    '            Return reader
    '        End Function


    ''' <summary>
    ''' uses itextsharp 4.1.6 to convert any pdf to 1.4 compatible pdf
    ''' </summary>
    ''' <param name="sFilename"></param>
    ''' <returns></returns>
    Private Function ReturnCompatiblePdf(ByVal sFilename As String) As MemoryStream

        Dim reader As New iTextSharp.text.pdf.PdfReader(sFilename)
        Dim output_stream As New MemoryStream

        ' we retrieve the total number of pages
        Dim n As Integer = reader.NumberOfPages
        ' step 1: creation of a document-object
        Dim document As New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1))
        ' step 2: we create a writer that listens to the document
        Dim writer As iTextSharp.text.pdf.PdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(document, output_stream)
        'write pdf that pdfsharp can understand
        writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_4)
        ' step 3: we open the document
        document.Open()
        Dim cb As iTextSharp.text.pdf.PdfContentByte = writer.DirectContent
        Dim page As iTextSharp.text.pdf.PdfImportedPage

        Dim rotation As Integer

        Dim i As Integer = 0
        While i < n
            i += 1
            document.SetPageSize(reader.GetPageSizeWithRotation(i))
            document.NewPage()
            page = writer.GetImportedPage(reader, i)
            rotation = reader.GetPageRotation(i)
            If rotation = 90 OrElse rotation = 270 Then
                cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, _
                reader.GetPageSizeWithRotation(i).Height)
            Else
                cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, _
                0)
            End If
        End While

        '---- Keep the stream open!
        writer.CloseStream = False

        ' step 5: we close the document
        document.Close()

        Return output_stream

    End Function
    '    End Module

    Public Sub INS_MODIFICA(ByVal MODIFICA As String, ByVal FILE As String)
        Dim document As PdfDocument
        Try
            document = PdfReader.Open(FILE)
ITEXTSTART:
            If MODIFICA = "" Then
                document.Info.Keywords = MODIFICA
            Else
                If document.Info.Keywords = "" Then
                    document.Info.Keywords += MODIFICA
                Else
                    document.Info.Keywords += " " & MODIFICA
                End If

            End If

            document.Save(FILE)
            document.Close()
        Catch EX As PdfSharpException
            Dim newName As MemoryStream = ReturnCompatiblePdf(FILE)
            Dim reader As New PdfDocument
            reader = PdfReader.Open(newName, PdfDocumentOpenMode.Modify)
            document = reader
            GoTo ITEXTSTART
        End Try

    End Sub
    Public Function LEGGI_MODIFICA(ByVal FILE As String)
        Dim document As PdfDocument
        Dim MODIFICA As String
        Try
            document = PdfReader.Open(FILE)
ITEXTSTART:
            MODIFICA = document.Info.Keywords
            document.Close()
        Catch EX As PdfSharpException
            Dim newName As MemoryStream = ReturnCompatiblePdf(FILE)
            Dim reader As New PdfDocument
            reader = PdfReader.Open(newName, PdfDocumentOpenMode.Modify)
            document = reader
            GoTo ITEXTSTART
        End Try
        Return MODIFICA
    End Function

    Public Function RIDIMENSIONA_PDF(ByVal fileorigine As String)

        '        private void testScaleADocument()
        '{

        '    PdfSharp.Drawing.XGraphics gfx = null;
        '    PdfSharp.Drawing.XRect rect;
        '    PdfSharp.Pdf.PdfPage newPage;

        '    //Create Source Document
        '    File.Copy(this.pdfFileForScaling, this.pdfFileForWriteTmp, true);

        '    //Open the source document as XPdfForm object
        '    PdfSharp.Drawing.XPdfForm form = PdfSharp.Drawing.XPdfForm.FromFile(this.pdfFileForWriteTmp);

        '    // Create the output document
        'PdfSharp.Pdf.PdfDocument(outputDocument)
        '        = new PdfSharp.Pdf.PdfDocument();

        '    for (int i = 0; i < form.PageCount; i++)
        '    {
        '        //Create a new page in the output document, which returns
        '        //a new page object relative to the output document
        '        newPage = outputDocument.AddPage();

        '        //Create a graphics element from the OUTPUT page
        '        gfx = PdfSharp.Drawing.XGraphics.FromPdfPage(newPage);

        '        //Set the source page number to indicate which page number to 
        '        //work with.  The page number is one-based.
        '        form.PageNumber = i + 1;
        '        rect = new PdfSharp.Drawing.XRect(0, 0, newPage.Width, newPage.Height);

        '        //Set the scaling, which affects operations that follow.
        '        //Must be set prior to operations that require scaling.
        '        gfx.ScaleTransform(0.5);

        '        // Draw the page identified by the page number (set above)
        '        // as an image into a XRect
        '        gfx.DrawImage(form, rect);

        '    }

        '    //Write the new output PDF file to disk.
        '    outputDocument.Save(this.pdfFileForScalingWrite);

        '    //Cleanup
        '    form.Dispose();
        '    outputDocument.Close();
        '    if (gfx != null)
        '        gfx.Dispose();

        '    //View
        '    Process.Start(this.pdfFileForScalingWrite);
        '}


        Dim gfx As PdfSharp.Drawing.XGraphics = Nothing
        Dim rect As PdfSharp.Drawing.XRect
        Dim newPage As PdfSharp.Pdf.PdfPage

        Dim file_modificato As String
        Dim document As PdfDocument
        'copio il file originale 
        Dim tempfile1 = Application.StartupPath & "\" & dati_stampa.Tempfile & ".pdf"
        File.Copy(fileorigine, tempfile1, True)


        'Open the source document as XPdfForm object
        Dim Form As PdfSharp.Drawing.XPdfForm = PdfSharp.Drawing.XPdfForm.FromFile(fileorigine)

        ' Create the output document
        Dim outputDocument = New PdfSharp.Pdf.PdfDocument()

        For I = 1 To Form.PageCount

            'Create a new page in the output document, which returns
            'a new page object relative to the output document
            newPage = outputDocument.AddPage()
            newPage.Size = PageSize.A4
            'Create a graphics element from the OUTPUT page
            gfx = PdfSharp.Drawing.XGraphics.FromPdfPage(newPage)

            '        //Set the source page number to indicate which page number to 
            '        //work with.  The page number is one-based.
            Form.PageNumber = I
            If I = 1 Then
                PUNTOSOPRA = (Form.Page.Height.Value - (newPage.Height.Value * SCALARIDIMY)) / 2
                PUNTOSOTTO = (newPage.Height.Value * SCALARIDIMY) + PUNTOSOPRA
                rect = New PdfSharp.Drawing.XRect((Form.Page.Width.Value - newPage.Width.Value) / 2, ((Form.Page.Height.Value - (newPage.Height.Value * SCALARIDIMY)) / 2), newPage.Width, newPage.Height)

                '        //Set the scaling, which affects operations that follow.
                '        //Must be set prior to operations that require scaling.
                gfx.ScaleTransform(1, SCALARIDIMY)

                '        // Draw the page identified by the page number (set above)
                '        // as an image into a XRect
                gfx.DrawImage(Form, rect)
            Else
                rect = New PdfSharp.Drawing.XRect(0, 0, newPage.Width, newPage.Height)
                gfx.DrawImage(Form, rect)
            End If
        Next
        outputDocument.Save(tempfile1)
        Form.Dispose()
        outputDocument.Close()


        Return tempfile1
    End Function
End Module
